package com.example.service.util.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.example.service.util.constants.MessageConstants;
import com.example.service.util.properties.SmsPropertiesVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * @Author juzipi
 * @Date 2021/7/18 11:38
 * @Info
 */
@Component
public class MessageService {


    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    public Boolean sendCodeMessage(String phone,String captcha){
        Client client = null;
        try {
            client = MessageService.createClient(SmsPropertiesVariable.ACCESS_KEY_ID, SmsPropertiesVariable.SECRET);

            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            sendSmsRequest.setSignName(MessageConstants.SIGN_NAME_VALUE);
            sendSmsRequest.setTemplateCode(MessageConstants.TEMPLATE_CODE_VALUE);
            sendSmsRequest.setPhoneNumbers(phone);
            //模板参数，必须要是json格式
            // {
            //    "msg": "...",
            //    "code": ...
            //} 这种格式的
            HashMap<String, Object> templateParam = new HashMap<>();
            templateParam.put(MessageConstants.CODE,captcha);
            sendSmsRequest.setTemplateParam(JSONObject.toJSONString(templateParam));
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            logger.info("发送短信返回结果 -------------> "+sendSmsResponse.getBody().message);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }



    /**
     * 使用AK&SK初始化账号Client ----> 这是新版写法
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }




}
